package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    private SpecParamService paramService;

    @Override
    public List<SpecGroupDTO> queryGroupByCategory(Long cid) {

        List<SpecGroup> specGroups = this.query().eq("category_id", cid).list();

        return SpecGroupDTO.convertEntityList(specGroups);
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long cid) {
        List<SpecGroupDTO> specGroupDTOS = queryGroupByCategory(cid);

        List<SpecParamDTO> specParamDTOS =SpecParamDTO.convertEntityList(this.paramService.query().eq("category_id",cid).list());

        Map<Long, List<SpecParamDTO>> paramMap = specParamDTOS
                .stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        specGroupDTOS.forEach(specGroupDTO -> specGroupDTO.setParams(paramMap.get(specGroupDTO.getId())));
        return specGroupDTOS;
    }
}
